#include "degfx/font.h"

void mx__font_bitchar(MX_BITMAP * bitmap, const MX_RECT * charrect, const MX_RECT * drawrect, const unsigned char *data, unsigned int width,
					  MX_PIXEL color)
{
	int r;
	unsigned int bpix;
	unsigned int xoff, yoff, x2off;

	xoff = drawrect->x1 - charrect->x1;
	yoff = drawrect->y1 - charrect->y1;
	x2off = charrect->x2 - drawrect->x2;

	/* Move the data over to correct to the mx_clipping on the top and the
	   width of the character */
	data += ((yoff * width) / 8) - 1;

	for (r = drawrect->y1; r <= drawrect->y2; r++) {

		MX_BITMAP_ITER iter = mx_bitmap_iter(bitmap, drawrect->x1, r);
		const MX_BITMAP_ITER end = mx_bitmap_iter(bitmap, drawrect->x2, r);

		/* Move the data over to correct for the clipping on the left */
		bpix = 0x100 >> (xoff % 8);
		data += (xoff / 8) + 1;

		while (iter <= end) {

			/* Go one pixel to right, and maybe to the next data byte */
			bpix >>= 1;
			if (!bpix) {
				bpix = 0x80;
				++data;
			}

			/* Foreground pixel */
			if ((*data) & bpix)
				*iter = MXBLEND(color, *iter);

			++iter;
		}

		/* Skip data to the right if the right side is clipped */
		data += (x2off / 8);
	}
}
